package org.outlook.xnotepad.command.action;

import java.text.MessageFormat;
import java.util.Random;

/**
 * function:
 * @author watson  email: watson.wu@hotmail.com
 * @date 2009-12-22
 */
public class SimpleCommandAction implements CommandAction {
	
	final static String FORMAT = "[{0}-{1}]";
	private final static MessageFormat MESSAGEFORMAT = new MessageFormat(FORMAT);
	private Integer setup=1;
	private Integer start;
	private Integer end;
	private boolean isChar=false;
	public SimpleCommandAction(String text) throws Exception {
		Object[] objects = MESSAGEFORMAT.parse(text);
		try {
			start = Integer.valueOf(objects[0].toString());
		} catch (Exception e) {
			start = Character.getNumericValue((Character)objects[0]);
			isChar=true;
		}
		try {
			end = Integer.valueOf(objects[1].toString());
		} catch (Exception e) {
			end = Character.getNumericValue((Character)objects[1]);
			isChar=true;
		}
		if(text.endsWith("}")) {
			char ch=text.subSequence(text.length()-2, text.length()-1).charAt(1);
			if(ch=='r')
				setup = -1;
			else
				setup=Integer.valueOf(objects[2].toString().substring(1, 2));
		}
	}

//	@Override
	public String getValue(int index) {
		int value;
		if(setup>0)
			value=start+setup*(index-1);
		else
			value=getRandom();
		if(isChar)
			return new Character((char)value).toString();
		else
			return String.valueOf(value);
	}

	private Random random=new Random();
	private int getRandom() {
		final boolean b = start<end;
		int value = random.nextInt(b?end:start);
		if(b && value>start)
			return value;
		else if(!b && value>end)
			return value;
		else 
			return getRandom();
	}

}